import Cookies from 'js-cookie'

import { constantRoutes, asyncRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/**
 * 筛选出显示的菜单
 * @param {*} routes
 */

function filterShowRouter(routes) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (!tmp.hidden) {
      if (tmp.children) {
        tmp.children = filterShowRouter(tmp.children)
        // 如果无子菜单，则此菜单丢弃，依次向上类推；所以定义菜单时候，如果要显示主菜单，至少需要一个子菜单
        if (tmp.children.length === 0) {
          return
        }
      }
      res.push(tmp)
    }
  })

  return res
}

// 判断当前地址是否在某个菜单里
function checkPathInRouter(router, path) {
  if (router.path && router.path === path) {
    return true
  }
  if (router.path) {
    return false
  }
  for (const i in router.children) {
    if (checkPathInRouter(router.children[i], path)) {
      return true
    }
  }
  return false
}

const state = {
  routes: [], // 主路由
  menuList: [], // 主菜单
  menuIndex: Cookies.get('menuIndex') || -1, // 主菜单激活序号
  sideMenu: []// 左侧菜单
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENU_LIST: (state, menu) => {
    state.menuList = menu
  },
  SET_MENU_INDEX: (state, menuIndex) => {
    state.menuIndex = menuIndex
    Cookies.set('menuIndex', menuIndex)
  },
  CHECK_MENU_INDEX: (state, pathTo) => {
    // 获取当前地址的主菜单序列并激活
    // 细节：通过对比当前地址的首个path 和主菜单的path,如果匹配成功则激活当前菜单
    // 用途：有些链接不是主动点击菜单跳转的，是通过点击主面板的快捷链接跳转，这个时候主菜单没有跟随激活改变
    var path = ''
    for (const p in pathTo.matched) {
      path = pathTo.matched[p].path
      if (path) {
        break
      }
    }
    const menuList = state.menuList
    for (const i in menuList) {
      if (checkPathInRouter(menuList[i], path)) {
        if (state.menuIndex !== parseInt(i)) {
          mutations.SET_MENU_INDEX(state, i)
        }
        return
      }
    }
  },
  SET_SIDE_MENU: (state, sideMenu) => {
    state.sideMenu = sideMenu
  },
  CLEAR_MENU_LIST: (state) => {
    state.menuIndex = -1
    Cookies.set('menuIndex', -1)
    state.menuList = []
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_MENU_LIST', filterShowRouter(accessedRoutes))
      resolve(accessedRoutes)
    })
  },
  SetMenuIndex({ commit }, menuIndex) {
    commit('SET_MENU_INDEX', menuIndex)
  },
  CheckMenuIndex({ commit }, pathTo) {
    commit('CHECK_MENU_INDEX', pathTo)
  },
  ClearMenuList({ commit }) {
    commit('CLEAR_MENU_LIST')
  }

}

export default {
  state,
  mutations,
  actions
}
